package com.cx.bank.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.cx.bank.actionsforms.LoginAndRegisterActionForm;
import com.cx.bank.manager.ManagerImpl;
import com.cx.bank.model.UserBean;

public class LoginAndRegisterActions extends DispatchAction {
	//获取UserBean对象，用来存放用户数据，存入用户名和密码
	UserBean user = new UserBean();
	// 实例化业务层对象managerimp，注：managerimp为单例对象
	ManagerImpl managerimp = ManagerImpl.getInstance();
	
	
	/**
	 * 如果没有传递任何标识参数（如command参数），则默认调用unspecified方法
	 */
	protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("LoginAndRegisterActions=>>unspecified()");
		ActionForward listActionForward = new ActionForward("/index.jsp", true);
		return listActionForward;
	}

	/**
	 * 登录
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 从HttpServletRequest得到session
		HttpSession session = request.getSession();

		LoginAndRegisterActionForm laf = (LoginAndRegisterActionForm) form;
		
		user.setName(laf.getUsername());
		user.setPassword(laf.getPassword());
		
		
		// 将登录方法的返回结果设置给flag，成功则为true
		boolean flag = managerimp.login(user);

		if (flag) {
			// 登录成功则将用户名放入session中，使后续页面可以得到用户名
			session.setAttribute("name", laf.getUsername());
			// 跳转至操作界面
			return mapping.findForward("login_success");
		} else {
			// 跳转至错误界面
			return mapping.findForward("login_error");
		}
	}
	
	
	/**
	 * 注册
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward register(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		LoginAndRegisterActionForm laf = (LoginAndRegisterActionForm) form;
		user.setName(laf.getReusername());
		user.setPassword(laf.getRepassword());
		// 将登录方法的返回结果设置给flag，成功则为true
		boolean flag = managerimp.register(user);

		if (flag) {
			// 跳转至操作界面
			return mapping.findForward("register_success");
		} else {
			// 跳转至错误界面
			return mapping.findForward("register_error");
		}
	}
}
